<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
    <el-form-item label="创建时间">
      <el-date-picker
        style="width: 240px"
        v-model="dateRangeCreateTime"
        value-format="YYYY-MM-DD HH:mm:ss"
        type="daterange"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
      ></el-date-picker>
    </el-form-item>
    <el-form-item style="padding-left: 80px">
      <el-button size="small" type="primary" icon="search" @click="handleQuery">查询</el-button>
      <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>
  <div class="analysis-page">
    <div id="myElement" style="width: 50%;height: 380px;"></div>
    <div id="myElementRight" style="width: 50%;height: 380px;"></div>
  </div>
</template>

<script setup>
import VChart from '@visactor/vchart';
import { getTotalCountStatistics } from '@/api/statisticalAnalysis';

const pieChartData = ref([]);
const barChartData = ref([]);
const dateRangeCreateTime = ref([]);
const renderChart = () => {
  const spec = {
    type: 'pie',
    data: [
      {
        id: 'id0',
        values: pieChartData.value
      }
    ],
    outerRadius: 0.8,
    innerRadius: 0.5,
    padAngle: 0.6,
    valueField: 'value',
    categoryField: 'type',
    pie: {
      style: {
        cornerRadius: 10
      },
      state: {
        hover: {
          outerRadius: 0.85,
          stroke: '#000',
          lineWidth: 1
        },
        selected: {
          outerRadius: 0.85,
          stroke: '#000',
          lineWidth: 1
        }
      }
    },
    title: {
      visible: true,
      text: '要素数据总览'
    },
    legends: {
      visible: true,
      orient: 'left'
    },
    label: {
      visible: true
    },
    tooltip: {
      mark: {
        content: [
          {
            key: datum => datum['type'],
            value: datum => datum['value'] + '%'
          }
        ]
      }
    }
  };

  const vchart = new VChart(spec, { dom: "myElement" });
  vchart.renderSync();
  window['vchart'] = vchart;
}

const renderChartRight = () => {
  const spec = {
    type: 'bar',
    data: [
      {
        id: 'barData',
        values: barChartData.value
      }
    ],
    direction: 'horizontal',
    xField: 'value',
    yField: 'name',
    seriesField: 'name',
    padding: { right: 50, left: 10 },
    axes: [
      {
        orient: 'bottom',
        visible: false,
        nice: false
      },
      {
        orient: 'left',
        maxWidth: 65,
        label: {
          autoLimit: true
        },
        domainLine: {
          visible: false
        },
        tick: {
          visible: false
        }
      }
    ],
    stackCornerRadius: 0,
    bar: {
      style: {
        cornerRadius: [5, 5, 5, 5],
        height: 10
      }
    },
    barBackground: {
      visible: true,
      style: {
        cornerRadius: [5, 5, 5, 5],
        height: 10
      },
      state: {
        hover: {
          stroke: '#D9D9D9',
          lineWidth: 1
        }
      }
    },
    extensionMark: [
      {
        type: 'text',
        dataId: 'barData',
        visible: true,
        style: {
          text: datum => datum.value,
          fontSize: 12,
          x: (datum, ctx) => {
            return ctx.getRegion().getLayoutRect().width + 10;
          },
          y: (datum, ctx) => {
            return ctx.valueToY([datum.province]) + ctx.yBandwidth() / 2;
          },
          textBaseline: 'middle',
          textAlign: 'left',
          fill: '#595959',
          size: 20
        }
      }
    ],
    crosshair: {
      yField: {
        visible: false
      }
    },
    tooltip: {
      mark: {
        title: {
          visible: false
        }
      },
      dimension: {
        title: {
          visible: false
        }
      },
      style: {
        shape: {
          shapeType: 'circle'
        }
      }
    }
  };

  const vchart = new VChart(spec, { dom: "myElementRight" });
  vchart.renderSync();

  // 只为了方便控制台调试用，不要拷贝
  window['vchart'] = vchart;
}
  
const getAllTotalCountStatistics = async () => {
  if (!dateRangeCreateTime.value || dateRangeCreateTime.value.length === 0) {
    return;
  }
  const { data } = await getTotalCountStatistics(dateRangeCreateTime.value[0], dateRangeCreateTime.value[1]);
  // { type: '模型库', value: '46.60' },
  const keyMap = {
    'calculation': '算例库',
    'layup': '铺层库',
    'model': '模型库',
    'section': '型材库',
    'analysis': '算法库'
  }
  for(let key in data) {
    pieChartData.value.push({
      type: keyMap[key],
      value: data[key]
    })
    barChartData.value.push({
      name: keyMap[key],
      value: data[key],
      type: 'common'
    })
  }
  renderChart();
  renderChartRight();
} 
const handleQuery = () => {
  getAllTotalCountStatistics();
}                                                                                   
const resetQuery = () => {
  initTimeAndData();                                                                               
}              
const initTimeAndData = () => {
  // 获取当前日期和时间
  const now = new Date();
  // 获取当前年、月、日、时、分、秒
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth() + 1; // 月份从0开始，所以要加1
  const currentDay = now.getDate();
  const currentHours = now.getHours();
  const currentMinutes = now.getMinutes();
  const currentSeconds = now.getSeconds();
  const endTime =  `${currentYear}-${currentMonth < 10 ? '0' : ''}${currentMonth}-${currentDay < 10 ? '0' : ''}${currentDay} ${currentHours < 10 ? '0' : ''}${currentHours}:${currentMinutes < 10 ? '0' : ''}${currentMinutes}:${currentSeconds < 10 ? '0' : ''}${currentSeconds}`;
  // 往前推算12个月
  const monthsToSubtract = 12;
  const previousDate = new Date(now);
  previousDate.setMonth(previousDate.getMonth() - monthsToSubtract);
  // 获取推算后的年、月、日、时、分、秒（注意：小时、分钟、秒不会变）
  const previousYear = previousDate.getFullYear();
  const previousMonth = previousDate.getMonth() + 1; // 月份从0开始，所以要加1
  const previousDay = previousDate.getDate();
  const startTime = `${previousYear}-${previousMonth < 10 ? '0' : ''}${previousMonth}-${previousDay < 10 ? '0' : ''}${previousDay} ${currentHours < 10 ? '0' : ''}${currentHours}:${currentMinutes < 10 ? '0' : ''}${currentMinutes}:${currentSeconds < 10 ? '0' : ''}${currentSeconds}`;
  dateRangeCreateTime.value = [startTime, endTime];
  getAllTotalCountStatistics();
}
onMounted(() => {
  // renderChart();      
  // renderChartRight();       
  initTimeAndData();              
});                                                                                   
                                                         
</script>

<style lang="scss" scoped>
.analysis-page {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>